/*
 * Shell.scala
 */

package acorn.jash

import java.lang.System._

// For scala-2.9
import scala.tools.jline.console._
import scala.tools.jline.console.completer._

// For scala-2.8, the original JLine should be used instead
// import jline._

object Shell {

  def main(args:Array[String]) {

    for (i <- 0 until args.length) {
      args(i) match {
        case "-debug" => debugging = true
        case s:String => try {wd = new Path(s)}
                         catch {case e:JashException => println(e getMessage)}
      }
    }
    
    while (true) {
      val input = JConsole readLine (Prompt.ps1)
      input match {
        case null =>
        case "" => Shell.debug("empty str received.")
        case "exit" => exit(0)
        case _ => try {
          val expr = parser parse input
          expr eval
        }
        catch {
          case je:JashException => println(je getMessage)
          case e:Exception => e printStackTrace
        }
      }
    }
  }

  def debug(msg:String) {
    if (debugging) println("[DEBUG] " + msg)
  }


  /**
   * user's current working directory,
   * it's the home directory be default
   */
  var wd:Path = Path.home


  /**
   * last working directory
   */
  var lwd:Path = Path.home

  val parser = new Parser

  var debugging = false
}

object JConsole {

  // Disable jline in emacs.
  val emacs = "t" == getenv("EMACS")

  def readLine(prompt:String):String = {
    val input = if (emacs) Console readLine prompt
                else reader readLine prompt

    Shell.debug("input => [" + input + "]")
    if (null != input) input trim else null
  }

  lazy val reader = new ConsoleReader

  if (!emacs) {
    val completers = new java.util.LinkedList[Completer]
    completers.add(new PathCompleter)

    val argCompleter = new ArgumentCompleter(completers)
    argCompleter setStrict false
    reader addCompleter argCompleter

    reader setBellEnabled false
  }
}

